import React, { useState, useEffect } from 'react';
import { DatePicker, Radio } from 'antd';
import moment from 'moment';

const { WeekPicker, MonthPicker } = DatePicker;

// 周月日期切换控件
const WeekMonthDate = React.forwardRef(
    (
        {
            reportType = 1, // 日期类型，1：周；2：月
            value,
            onChange,
            format = 'YYYY-MM-DD',
            width = 120,
            ...rest
        },
        ref
    ) => {
        const [dateType, setDateType] = useState(Number(reportType) === 1 ? 'week' : 'month');
        const [date, setDate] = useState(value ? moment(value) : moment());

        useEffect(() => {
            // 根据date输出日期范围
            const rangeDate = {
                dateType,
                reportType: dateType === 'week' ? 1 : 2,
                startDate: date.startOf(dateType).format(format),
                endDate: date.endOf(dateType).format(format)
            };

            if (onChange) {
                onChange(rangeDate);
            }
            // console.log(rangeDate);
        }, [date, dateType]);
        // console.log(date.format(format));

        return (
            <div ref={ref}>
                <Radio.Group
                    onChange={e => {
                        setDateType(e.target.value);
                        setDate(moment());
                    }}
                    value={dateType}
                    style={{ marginRight: 10 }}
                >
                    <Radio.Button value="week">周</Radio.Button>
                    <Radio.Button value="month">月</Radio.Button>
                </Radio.Group>
                {dateType === 'week' && (
                    <WeekPicker
                        style={{ width }}
                        allowClear={false}
                        value={date}
                        onChange={e => {
                            setDate(e);
                        }}
                        {...rest}
                    />
                )}
                {dateType === 'month' && (
                    <MonthPicker
                        style={{ width }}
                        value={date}
                        allowClear={false}
                        onChange={e => {
                            setDate(e);
                        }}
                        {...rest}
                    />
                )}
            </div>
        );
    }
);
export default WeekMonthDate;
